<template>
  <div class="el-form">
    <slot />
  </div>
</template>

<script lang="ts">
export default {
  name: "ElForm"
};
</script>
<script lang="ts" setup>
import { PropType, provide, ref } from "vue";
import { Rules } from "async-validator";
import { key, FormItem } from "./type";
import { useEventHub } from "../utils/index";

const props = defineProps({
  model: { type: Object, require: true, default: () => ({}) },
  rules: { type: Object as PropType<Rules> }
});

const items = ref<FormItem[]>([]);

const hub = useEventHub();

hub.on("addFormItem", (item:FormItem) => {
  items.value.push(item);
});

provide(key, {
  model: props.model,
  rules: props.rules
});

defineExpose({
  validate(cb:(isValid:boolean) =>void) {
    const task = items.value.map(item => item.validate());
    return Promise.all(task).then(() => cb(true)).catch(() => cb(false));
  }
});
</script>

<style lang="scss" scope>
@import '../styles/mixins';

@include b(form) {
  margin-top:20px;
  box-sizing: border-box;
  flex-shrink: 0;
  width:300px;
}
</style>